from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib import messages
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
import json
import csv
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill
from openpyxl.utils import get_column_letter
from .models import Bicycle, ViolationRecord, CollegeUser, ViolationSecretKey
from .forms import BicycleForm, ViolationForm, CollegeUserForm, ViolationSecretKeyForm, ViolationFormWithSecret, BicycleEditFormWithSecret


def admin_login(request):
    """管理员登录"""
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(request, username=username, password=password)
        
        if user is not None:
            login(request, user)
            messages.success(request, f'欢迎回来，{user.username}！')
            # 检查是否是学院管理员
            try:
                college_user = CollegeUser.objects.get(user=user)
                return redirect('bike:admin_dashboard')
            except CollegeUser.DoesNotExist:
                # 普通用户登录后跳转到自行车列表
                return redirect('bike:bike_list')
        else:
            messages.error(request, '用户名或密码错误。')
    
    return render(request, 'admin/login.html')


@login_required
def admin_logout(request):
    """管理员登出"""
    logout(request)
    messages.info(request, '您已成功登出。')
    return redirect('bike:admin_login')


@login_required
def admin_dashboard(request):
    """管理后台首页（仅超级管理员和学院管理员）"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    college = None
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        college = college_user.college
        is_super_admin = college_user.is_super_admin
    except CollegeUser.DoesNotExist:
        # 普通用户不能访问管理后台
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:bike_list')
    
    # 获取统计数据
    if is_super_admin:
        # 超级管理员查看所有数据
        total_bikes = Bicycle.objects.count()
        pending_violations = ViolationRecord.objects.filter(status='pending').count()
        processing_violations = ViolationRecord.objects.filter(status='processing').count()
        resolved_violations = ViolationRecord.objects.filter(status='resolved').count()
        total_violations = ViolationRecord.objects.count()
        college_stats = []
        for choice in Bicycle.COLLEGE_CHOICES:
            college_code = choice[0]
            count = Bicycle.objects.filter(college=college_code).count()
            college_stats.append({
                'name': choice[1],
                'count': count
            })
    elif college_user and college:
        # 学院管理员只查看本学院数据
        total_bikes = Bicycle.objects.filter(college=college).count()
        pending_violations = ViolationRecord.objects.filter(
            bicycle__college=college,
            status='pending'
        ).count()
        processing_violations = ViolationRecord.objects.filter(
            bicycle__college=college,
            status='processing'
        ).count()
        resolved_violations = ViolationRecord.objects.filter(
            bicycle__college=college,
            status='resolved'
        ).count()
        total_violations = ViolationRecord.objects.filter(
            bicycle__college=college
        ).count()
        college_stats = []
    else:
        # 普通用户查看所有数据
        total_bikes = Bicycle.objects.count()
        pending_violations = ViolationRecord.objects.filter(status='pending').count()
        processing_violations = ViolationRecord.objects.filter(status='processing').count()
        resolved_violations = ViolationRecord.objects.filter(status='resolved').count()
        total_violations = ViolationRecord.objects.count()
        college_stats = []
        for choice in Bicycle.COLLEGE_CHOICES:
            college_code = choice[0]
            count = Bicycle.objects.filter(college=college_code).count()
            college_stats.append({
                'name': choice[1],
                'count': count
            })
    
    if is_super_admin:
        recent_bikes = Bicycle.objects.order_by('-created_at')[:5]
        recent_violations = ViolationRecord.objects.order_by('-created_at')[:5]
    elif college_user and college:
        recent_bikes = Bicycle.objects.filter(college=college).order_by('-created_at')[:5]
        recent_violations = ViolationRecord.objects.filter(
            bicycle__college=college
        ).order_by('-created_at')[:5]
    else:
        recent_bikes = Bicycle.objects.order_by('-created_at')[:5]
        recent_violations = ViolationRecord.objects.order_by('-created_at')[:5]
    
    context = {
        'college_user': college_user,
        'is_super_admin': is_super_admin,
        'total_bikes': total_bikes,
        'pending_violations': pending_violations,
        'processing_violations': processing_violations,
        'resolved_violations': resolved_violations,
        'total_violations': total_violations,
        'college_stats': college_stats,
        'recent_bikes': recent_bikes,
        'recent_violations': recent_violations,
    }
    
    return render(request, 'admin/dashboard.html', context)


@login_required
def user_management(request):
    """用户管理页面（仅超级管理员和学院管理员）"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:bike_list')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:bike_list')
    
    # 获取所有用户
    users = CollegeUser.objects.all().order_by('-created_at')
    
    # 分页
    from django.core.paginator import Paginator
    paginator = Paginator(users, 10)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'college_user': college_user,
    }
    
    return render(request, 'admin/user_management.html', context)


@login_required
def user_add(request):
    """添加用户（仅超级管理员和学院管理员）"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:bike_list')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:bike_list')
    
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        college = request.POST.get('college')
        is_admin = request.POST.get('is_admin') == 'on'
        is_super_admin = request.POST.get('is_super_admin') == 'on'
        
        # 验证必填字段
        if not username or not password or not college:
            messages.error(request, '请填写所有必填字段！')
        # 验证用户名是否已存在
        elif User.objects.filter(username=username).exists():
            messages.error(request, '用户名已存在！')
        else:
            try:
                # 创建Django用户
                user = User.objects.create_user(username=username, password=password)
                
                # 创建学院用户
                college_user = CollegeUser.objects.create(
                    user=user,
                    college=college,
                    is_admin=is_admin,
                    is_super_admin=is_super_admin
                )
                
                messages.success(request, f'用户 {username} 创建成功！')
                return redirect('bike:user_management')
            except Exception as e:
                messages.error(request, f'创建用户失败：{str(e)}')
    
    # 学院选择 - 使用模型中的选择
    from .models import Bicycle
    COLLEGE_CHOICES = Bicycle.COLLEGE_CHOICES
    
    context = {
        'college_user': college_user,
        'college_choices': COLLEGE_CHOICES,
    }
    
    return render(request, 'admin/user_add.html', context)


@login_required
def user_edit(request, user_id):
    """编辑用户权限（仅超级管理员和学院管理员）"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:bike_list')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:bike_list')
    
    from django.shortcuts import get_object_or_404
    target_user = get_object_or_404(CollegeUser, id=user_id)
    
    if request.method == 'POST':
        # 更新权限
        target_user.is_admin = request.POST.get('is_admin') == 'on'
        target_user.is_super_admin = request.POST.get('is_super_admin') == 'on'
        target_user.college = request.POST.get('college')
        
        # 更新用户名
        new_username = request.POST.get('username', '').strip()
        if new_username and new_username != target_user.user.username:
            # 检查用户名是否已存在
            if User.objects.filter(username=new_username).exclude(id=target_user.user.id).exists():
                messages.error(request, f'用户名 {new_username} 已存在。')
            else:
                target_user.user.username = new_username
                target_user.user.save()
        
        # 更新密码
        new_password = request.POST.get('password', '').strip()
        if new_password:
            target_user.user.set_password(new_password)
            target_user.user.save()
        
        target_user.save()
        messages.success(request, f'用户 {target_user.user.username} 的信息已更新。')
        return redirect('bike:user_management')
    
    context = {
        'target_user': target_user,
        'college_user': college_user,
        'college_choices': Bicycle.COLLEGE_CHOICES,
    }
    
    return render(request, 'admin/user_edit.html', context)


@login_required
def user_delete(request, user_id):
    """删除用户（仅超级管理员）"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        if not college_user.is_super_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:admin_dashboard')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限。')
        return redirect('bike:admin_login')
    
    from django.shortcuts import get_object_or_404
    target_user = get_object_or_404(CollegeUser, id=user_id)
    
    # 不能删除自己
    if target_user.id == college_user.id:
        messages.error(request, '不能删除自己的账户！')
        return redirect('bike:user_management')
    
    if request.method == 'POST':
        username = target_user.user.username
        target_user.user.delete()  # 这会级联删除CollegeUser
        messages.success(request, f'用户 {username} 已删除。')
        return redirect('bike:user_management')
    
    context = {
        'target_user': target_user,
        'college_user': college_user,
    }
    
    return render(request, 'admin/user_delete.html', context)


@login_required
def batch_delete(request):
    """批量删除自行车（仅超级管理员和学院管理员）"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            return JsonResponse({'success': False, 'message': '您没有权限执行此操作。'})
    except CollegeUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '您没有管理权限。'})
    
    if request.method == 'POST':
        print(f"批量删除 - POST请求")
        print(f"POST数据: {request.POST}")
        
        bike_ids = request.POST.getlist('bike_ids')
        print(f"选中的自行车ID: {bike_ids}")
        
        if not bike_ids:
            messages.error(request, '请选择要删除的自行车！')
            return redirect('bike:admin_bike_list')
        
        # 权限检查：超级管理员可以删除所有学院的自行车，普通管理员只能删除自己学院的
        if is_super_admin:
            bikes = Bicycle.objects.filter(id__in=bike_ids)
        elif college_user and is_admin:
            bikes = Bicycle.objects.filter(id__in=bike_ids, college=college_user.college)
        else:
            # 普通用户可以删除任意自行车
            bikes = Bicycle.objects.filter(id__in=bike_ids)
        
        print(f"找到 {bikes.count()} 辆自行车可以删除")
        
        count = 0
        for bike in bikes:
            print(f"正在删除自行车: {bike.bike_number}")
            bike.delete()
            count += 1
        
        messages.success(request, f'成功删除 {count} 辆自行车！')
        print(f"批量删除完成，共删除 {count} 辆自行车")
    else:
        print("批量删除 - GET请求，重定向到列表")
    
    return redirect('bike:admin_bike_list')




@login_required
def batch_export_qr(request):
    """批量导出二维码（仅超级管理员和学院管理员）"""
    print("=== 批量导出二维码请求 ===")
    print(f"请求方法: {request.method}")
    print(f"用户: {request.user}")
    
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            return JsonResponse({'success': False, 'message': '您没有权限执行此操作。'})
        print(f"学院用户: {college_user.college}, 超级管理员: {is_super_admin}")
    except CollegeUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '您没有管理权限。'})
    
    if request.method == 'POST':
        bike_ids = request.POST.getlist('bike_ids')
        print(f"收到的自行车ID: {bike_ids}")
        
        if not bike_ids:
            messages.error(request, '请选择要导出二维码的自行车！')
            return redirect('bike:admin_bike_list')
        
        # 权限检查
        if is_super_admin:
            bikes = Bicycle.objects.filter(id__in=bike_ids)
        elif college_user and is_admin:
            bikes = Bicycle.objects.filter(id__in=bike_ids, college=college_user.college)
        else:
            # 普通用户可以导出任意自行车
            bikes = Bicycle.objects.filter(id__in=bike_ids)
        
        print(f"找到 {bikes.count()} 辆自行车可以导出")
        
        # 检查是否有自行车
        if not bikes.exists():
            messages.error(request, '没有找到符合条件的自行车！')
            return redirect('bike:admin_bike_list')
        
        # 创建ZIP文件
        import zipfile
        import os
        from django.http import HttpResponse
        from django.conf import settings
        import io
        
        print(f"开始创建ZIP文件，自行车数量: {bikes.count()}")
        
        # 使用内存中的ZIP文件
        zip_buffer = io.BytesIO()
        
        with zipfile.ZipFile(zip_buffer, 'w', zipfile.ZIP_DEFLATED) as zip_file:
            # 按学院分组
            college_groups = {}
            files_added = 0
            
            for bike in bikes:
                if bike.qr_code:
                    college_name = bike.get_college_display()
                    if college_name not in college_groups:
                        college_groups[college_name] = []
                    college_groups[college_name].append(bike)
                    print(f"自行车 {bike.bike_number} 分组到 {college_name}")
            
            print(f"学院分组: {list(college_groups.keys())}")
            
            # 为每个学院创建文件夹并添加文件
            for college_name, college_bikes in college_groups.items():
                print(f"处理学院: {college_name}, 自行车数量: {len(college_bikes)}")
                for bike in college_bikes:
                    qr_path = os.path.join(settings.MEDIA_ROOT, str(bike.qr_code))
                    print(f"检查文件: {qr_path}, 存在: {os.path.exists(qr_path)}")
                    if os.path.exists(qr_path):
                        # 在ZIP中创建学院文件夹
                        zip_path = f"{college_name}/{bike.bike_number}.png"
                        zip_file.write(qr_path, zip_path)
                        files_added += 1
                        print(f"添加文件到ZIP: {zip_path}")
            
            # 如果没有添加任何文件，添加一个说明文件
            if files_added == 0:
                zip_file.writestr("说明.txt", "没有找到二维码文件，请确保自行车已生成二维码。")
                print("添加说明文件到ZIP")
        
        print(f"ZIP文件创建完成，添加了 {files_added} 个文件")
        
        # 如果没有添加任何文件，返回错误消息
        if files_added == 0:
            messages.error(request, '没有找到二维码文件，请确保选中的自行车已生成二维码！')
            return redirect('bike:admin_bike_list')
        
        # 准备响应
        zip_buffer.seek(0)
        zip_data = zip_buffer.getvalue()
        print(f"ZIP文件大小: {len(zip_data)} 字节")
        
        response = HttpResponse(zip_data, content_type='application/zip')
        response['Content-Disposition'] = 'attachment; filename="bike_qr_codes.zip"'
        response['Content-Length'] = len(zip_data)
        
        print("返回ZIP文件响应")
        return response
    
    return redirect('bike:admin_bike_list')


@login_required
def export_qr_codes(request):
    """导出二维码（所有管理员）"""
    try:
        college_user = CollegeUser.objects.get(user=request.user)
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限。')
        return redirect('bike:admin_login')
    
    # 根据权限获取自行车数据
    if college_user.is_super_admin:
        bikes_without_qr = Bicycle.objects.filter(qr_code__isnull=True).count()
        total_bikes = Bicycle.objects.count()
        bikes_with_qr = Bicycle.objects.filter(qr_code__isnull=False).count()
    else:
        bikes_without_qr = Bicycle.objects.filter(college=college_user.college, qr_code__isnull=True).count()
        total_bikes = Bicycle.objects.filter(college=college_user.college).count()
        bikes_with_qr = Bicycle.objects.filter(college=college_user.college, qr_code__isnull=False).count()
    
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'generate':
            # 批量生成二维码
            if college_user.is_super_admin:
                bikes = Bicycle.objects.filter(qr_code__isnull=True)
            else:
                bikes = Bicycle.objects.filter(college=college_user.college, qr_code__isnull=True)
            
            generated_count = 0
            for bike in bikes:
                if not bike.qr_code:
                    bike.generate_qr_code()
                    bike.save()
                    generated_count += 1
            
            messages.success(request, f'成功为 {generated_count} 辆自行车生成二维码。')
            return redirect('bike:export_qr_codes')
        
        elif action == 'export':
            # 导出二维码
            if college_user.is_super_admin:
                bikes = Bicycle.objects.all()
            else:
                bikes = Bicycle.objects.filter(college=college_user.college)
            
            # 创建ZIP文件
            import zipfile
            import os
            from django.http import HttpResponse
            from django.conf import settings
            
            response = HttpResponse(content_type='application/zip')
            response['Content-Disposition'] = 'attachment; filename="bike_qr_codes.zip"'
            
            with zipfile.ZipFile(response, 'w') as zip_file:
                # 按学院分组
                college_groups = {}
                for bike in bikes:
                    if bike.qr_code:
                        college_name = bike.get_college_display()
                        if college_name not in college_groups:
                            college_groups[college_name] = []
                        college_groups[college_name].append(bike)
                
                # 为每个学院创建文件夹并添加文件
                for college_name, college_bikes in college_groups.items():
                    for bike in college_bikes:
                        qr_path = os.path.join(settings.MEDIA_ROOT, str(bike.qr_code))
                        if os.path.exists(qr_path):
                            # 在ZIP中创建学院文件夹
                            zip_path = f"{college_name}/{bike.bike_number}.png"
                            zip_file.write(qr_path, zip_path)
            
            return response
    
    context = {
        'total_bikes': total_bikes,
        'bikes_with_qr': bikes_with_qr,
        'bikes_without_qr': bikes_without_qr,
        'college_user': college_user,
        'is_super_admin': college_user.is_super_admin,
    }
    
    return render(request, 'admin/export_qr_codes.html', context)


@login_required
def bike_list_admin(request):
    """自行车列表管理（仅超级管理员和学院管理员）"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    college = None
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        college = college_user.college
        is_super_admin = college_user.is_super_admin
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:bike_list')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:bike_list')
    
    # 获取查询参数
    search = request.GET.get('search', '')
    category = request.GET.get('category', '')
    college_filter = request.GET.get('college', '')
    
    # 构建查询
    if is_super_admin:
        # 超级管理员可以查看所有学院的自行车
        bikes = Bicycle.objects.all()
        if college_filter:
            bikes = bikes.filter(college=college_filter)
    elif college_user and college:
        # 学院管理员只能查看本学院的自行车
        bikes = Bicycle.objects.filter(college=college)
    else:
        # 普通用户查看所有自行车
        bikes = Bicycle.objects.all()
        if college_filter:
            bikes = bikes.filter(college=college_filter)
    
    if search:
        bikes = bikes.filter(
            Q(bike_number__icontains=search) |
            Q(owner_name__icontains=search) |
            Q(owner_student_id__icontains=search) |
            Q(model__icontains=search)
        )
    
    if category:
        bikes = bikes.filter(category=category)
    
    # 分页
    paginator = Paginator(bikes, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'category': category,
        'college_filter': college_filter,
        'categories': Bicycle.CATEGORY_CHOICES,
        'colleges': Bicycle.COLLEGE_CHOICES,
        'college_user': college_user,
        'is_super_admin': is_super_admin,
    }
    
    return render(request, 'admin/bike_list.html', context)


@login_required
def bike_add(request):
    """添加自行车（仅超级管理员和学院管理员）"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:bike_list')
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:bike_list')
    
    # 调试信息
    print(f"用户: {request.user.username}")
    print(f"CollegeUser: {college_user}")
    print(f"is_super_admin: {is_super_admin}")
    print(f"is_admin: {is_admin}")
    
    if request.method == 'POST':
        # 在创建表单之前设置学院字段
        post_data = request.POST.copy()
        
        # 权限控制：设置学院
        if is_super_admin:
            # 超级管理员可以选择任意学院
            pass
        elif college_user and is_admin:
            # 学院管理员只能添加本学院
            post_data['college'] = college_user.college
        # 普通用户可以选择学院，不需要强制设置
        
        form = BicycleForm(post_data, request.FILES)
        if form.is_valid():
            bike = form.save(commit=False)
            bike.save()
            messages.success(request, f'自行车 {bike.bike_number} 添加成功！')
            return redirect('bike:admin_bike_list')
        else:
            # 表单验证失败，显示错误信息
            messages.error(request, '表单验证失败，请检查输入信息。')
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f'{field}: {error}')
    else:
        form = BicycleForm()
        # 设置默认学院
        if is_super_admin:
            # 超级管理员默认选择第一个学院
            from .models import Bicycle
            if Bicycle.COLLEGE_CHOICES:
                form.fields['college'].initial = Bicycle.COLLEGE_CHOICES[0][0]
        elif college_user and is_admin:
            # 学院管理员默认设置自己的学院
            form.fields['college'].initial = college_user.college
            form.fields['college'].widget.attrs['readonly'] = True
        else:
            # 普通用户可以选择学院，但默认计算机学院
            form.fields['college'].initial = 'computer'
            # 普通用户可以选择学院，不设置为只读
    
    context = {
        'form': form,
        'college_user': college_user,
        'is_super_admin': is_super_admin,
        'is_admin': is_admin,
    }
    
    return render(request, 'admin/bike_add.html', context)


@login_required
def bike_edit(request, bike_id):
    """编辑自行车"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
    except CollegeUser.DoesNotExist:
        # 普通用户也可以编辑自行车
        pass
    
    # 获取自行车对象
    if is_super_admin:
        bike = get_object_or_404(Bicycle, id=bike_id)
    elif college_user and is_admin:
        bike = get_object_or_404(Bicycle, id=bike_id, college=college_user.college)
    else:
        # 普通用户可以编辑任意自行车
        bike = get_object_or_404(Bicycle, id=bike_id)
    
    if request.method == 'POST':
        print(f"编辑自行车 {bike.bike_number} - POST请求")
        print(f"POST数据: {request.POST}")
        print(f"FILES数据: {request.FILES}")
        
        form = BicycleForm(request.POST, request.FILES, instance=bike)
        if form.is_valid():
            print("表单验证通过，正在保存...")
            form.save()
            messages.success(request, f'自行车 {bike.bike_number} 更新成功！')
            return redirect('bike:admin_bike_list')
        else:
            print(f"表单验证失败: {form.errors}")
            # 表单验证失败，显示错误信息
            messages.error(request, '表单验证失败，请检查输入信息。')
            for field, errors in form.errors.items():
                for error in errors:
                    messages.error(request, f'{field}: {error}')
    else:
        form = BicycleForm(instance=bike)
    
    context = {
        'form': form,
        'bike': bike,
        'college_user': college_user,
        'is_super_admin': is_super_admin,
        'is_admin': is_admin,
    }
    
    return render(request, 'admin/bike_edit.html', context)


@login_required
def bike_delete(request, bike_id):
    """删除自行车"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
    except CollegeUser.DoesNotExist:
        # 普通用户也可以删除自行车
        pass
    
    # 获取自行车对象
    if is_super_admin:
        bike = get_object_or_404(Bicycle, id=bike_id)
    elif college_user and is_admin:
        bike = get_object_or_404(Bicycle, id=bike_id, college=college_user.college)
    else:
        # 普通用户可以删除任意自行车
        bike = get_object_or_404(Bicycle, id=bike_id)
    
    # 直接删除自行车
    bike_number = bike.bike_number
    bike.delete()
    messages.success(request, f'自行车 {bike_number} 删除成功！')
    return redirect('bike:admin_bike_list')


@login_required
def violation_list(request):
    """违章记录列表（仅超级管理员和学院管理员）"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            messages.error(request, '您没有权限访问此页面。')
            return redirect('bike:violation_list')
        print(f"违章记录列表 - 用户: {request.user}, 学院: {college_user.college}, 超级管理员: {is_super_admin}")
    except CollegeUser.DoesNotExist:
        messages.error(request, '您没有管理权限，请使用前台功能。')
        return redirect('bike:violation_list')
    
    # 获取查询参数
    search = request.GET.get('search', '')
    violation_type = request.GET.get('violation_type', '')
    status = request.GET.get('status', '')
    college = request.GET.get('college', '')
    
    # 根据权限获取违章记录
    if is_super_admin:
        # 超级管理员可以管理所有违章记录
        violations = ViolationRecord.objects.select_related('bicycle').all()
        print(f"超级管理员查看所有违章记录，共 {violations.count()} 条")
    elif college_user and is_admin:
        # 学院管理员只能管理本学院违章记录
        violations = ViolationRecord.objects.filter(
            bicycle__college=college_user.college
        ).select_related('bicycle')
        print(f"学院管理员查看本学院违章记录，共 {violations.count()} 条")
    else:
        # 普通用户可以管理所有违章记录
        violations = ViolationRecord.objects.select_related('bicycle').all()
        print(f"普通用户查看所有违章记录，共 {violations.count()} 条")
    
    # 应用筛选条件
    if search:
        violations = violations.filter(
            Q(bicycle__bike_number__icontains=search) |
            Q(bicycle__owner_name__icontains=search) |
            Q(location__icontains=search) |
            Q(reporter_name__icontains=search)
        )
    
    if violation_type:
        violations = violations.filter(violation_type=violation_type)
    
    if status:
        violations = violations.filter(status=status)
    
    if college:
        violations = violations.filter(bicycle__college=college)
    
    # 按时间倒序排列
    violations = violations.order_by('-created_at')
    
    # 分页
    paginator = Paginator(violations, 15)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    # 获取选择项用于筛选器
    violation_types = ViolationRecord.VIOLATION_TYPES
    status_choices = ViolationRecord.STATUS_CHOICES
    colleges = Bicycle.COLLEGE_CHOICES
    
    # 统计信息
    total_violations = violations.count()
    pending_count = violations.filter(status='pending').count()
    processing_count = violations.filter(status='processing').count()
    resolved_count = violations.filter(status='resolved').count()
    dismissed_count = violations.filter(status='dismissed').count()
    
    context = {
        'page_obj': page_obj,
        'search': search,
        'violation_type': violation_type,
        'status': status,
        'college': college,
        'violation_types': violation_types,
        'status_choices': status_choices,
        'colleges': colleges,
        'total_violations': total_violations,
        'pending_count': pending_count,
        'processing_count': processing_count,
        'resolved_count': resolved_count,
        'dismissed_count': dismissed_count,
        'college_user': college_user,
        'is_super_admin': is_super_admin,
        'is_admin': is_admin,
    }
    
    return render(request, 'admin/violation_list.html', context)


@login_required
def violation_update_status(request, violation_id):
    """更新违章记录状态（仅超级管理员和学院管理员）"""
    # 检查用户权限
    college_user = None
    is_super_admin = False
    is_admin = False
    
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        is_super_admin = college_user.is_super_admin
        is_admin = college_user.is_admin
        # 只有超级管理员和学院管理员可以访问
        if not college_user.is_super_admin and not college_user.is_admin:
            return JsonResponse({'success': False, 'message': '您没有权限执行此操作。'})
        print(f"更新违章状态 - 用户: {request.user}, 学院: {college_user.college}, 超级管理员: {is_super_admin}")
    except CollegeUser.DoesNotExist:
        return JsonResponse({'success': False, 'message': '您没有管理权限。'})
    
    # 根据权限获取违章记录
    if is_super_admin:
        # 超级管理员可以更新所有违章记录
        violation = get_object_or_404(ViolationRecord, id=violation_id)
        print(f"超级管理员更新违章记录: {violation.id}")
    elif college_user and is_admin:
        # 学院管理员只能更新本学院违章记录
        violation = get_object_or_404(
            ViolationRecord, 
            id=violation_id,
            bicycle__college=college_user.college
        )
        print(f"学院管理员更新本学院违章记录: {violation.id}")
    else:
        # 普通用户可以更新所有违章记录
        violation = get_object_or_404(ViolationRecord, id=violation_id)
        print(f"普通用户更新违章记录: {violation.id}")
    
    if request.method == 'POST':
        print(f"收到POST请求，数据: {request.POST}")
        new_status = request.POST.get('status')
        print(f"更新状态为: {new_status}")
        
        if new_status in [choice[0] for choice in ViolationRecord.STATUS_CHOICES]:
            print(f"状态有效，更新违章记录 {violation.id} 状态从 {violation.status} 到 {new_status}")
            violation.status = new_status
            violation.save()
            print(f"违章记录 {violation.id} 状态更新成功")
            return JsonResponse({'success': True, 'message': '状态更新成功'})
        else:
            print(f"无效的状态: {new_status}")
            return JsonResponse({'success': False, 'message': f'无效的状态: {new_status}'})
    else:
        print(f"非POST请求: {request.method}")
    
    return JsonResponse({'success': False, 'message': '无效的请求方法'})




def mobile_bike_detail(request, bike_id):
    """手机端自行车详情页面"""
    bike = get_object_or_404(Bicycle, id=bike_id)
    
    # 检查是否需要秘钥验证
    active_key = ViolationSecretKey.get_active_key()
    need_secret_key = active_key is not None
    
    # 检查是否是编辑模式
    edit_mode = request.GET.get('edit') == 'true'
    
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'edit_bike':
            # 编辑自行车信息
            print(f"编辑自行车 - POST请求，需要秘钥: {need_secret_key}")
            print(f"POST数据: {request.POST}")
            print(f"FILES数据: {request.FILES}")
            
            if need_secret_key:
                edit_form = BicycleEditFormWithSecret(request.POST, request.FILES, instance=bike)
            else:
                edit_form = BicycleForm(request.POST, request.FILES, instance=bike)
                
            print(f"编辑表单验证结果: {edit_form.is_valid()}")
            if not edit_form.is_valid():
                print(f"编辑表单错误: {edit_form.errors}")
                
            if edit_form.is_valid():
                edit_form.save()
                messages.success(request, '自行车信息更新成功！')
                return redirect('bike:mobile_bike_detail', bike_id=bike_id)
            else:
                # 显示表单错误
                for field, errors in edit_form.errors.items():
                    for error in errors:
                        messages.error(request, f'{field}: {error}')
                edit_mode = True  # 保持编辑模式
        else:
            # 提交违章信息
            print(f"违章提交 - POST请求，需要秘钥: {need_secret_key}")
            print(f"POST数据: {request.POST}")
            print(f"FILES数据: {request.FILES}")
            
            if need_secret_key:
                form = ViolationFormWithSecret(request.POST, request.FILES)
            else:
                form = ViolationForm(request.POST, request.FILES)
                
            print(f"表单验证结果: {form.is_valid()}")
            if not form.is_valid():
                print(f"表单错误: {form.errors}")
                
            if form.is_valid():
                violation = form.save(commit=False)
                violation.bicycle = bike
                violation.save()
                messages.success(request, '违章信息提交成功！')
                return redirect('bike:mobile_bike_detail', bike_id=bike_id)
            else:
                # 显示表单错误
                for field, errors in form.errors.items():
                    for error in errors:
                        messages.error(request, f'{field}: {error}')
    else:
        if need_secret_key:
            form = ViolationFormWithSecret()
            edit_form = BicycleEditFormWithSecret(instance=bike)
        else:
            form = ViolationForm()
            edit_form = BicycleForm(instance=bike)
    
    # 获取该自行车的违章记录
    violations = bike.violations.all().order_by('-created_at')
    
    context = {
        'bike': bike,
        'form': form,
        'edit_form': edit_form,
        'violations': violations,
        'need_secret_key': need_secret_key,
        'edit_mode': edit_mode,
    }
    
    return render(request, 'mobile/bike_detail.html', context)


@login_required
def secret_key_management(request):
    """管理秘钥设置"""
    # 检查用户权限 - 只有超级管理员可以设置秘钥
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        if not college_user.is_super_admin:
            messages.error(request, '只有超级管理员可以设置管理秘钥！')
            return redirect('bike:admin_dashboard')
    except CollegeUser.DoesNotExist:
        messages.error(request, '只有超级管理员可以设置管理秘钥！')
        return redirect('bike:admin_dashboard')
    
    # 获取当前激活的秘钥
    current_key = ViolationSecretKey.get_active_key()
    
    if request.method == 'POST':
        form = ViolationSecretKeyForm(request.POST)
        if form.is_valid():
            # 禁用所有现有秘钥
            ViolationSecretKey.objects.filter(is_active=True).update(is_active=False)
            
            # 创建新秘钥
            secret_key = form.save(commit=False)
            secret_key.created_by = request.user
            secret_key.save()
            
            messages.success(request, f'管理秘钥已设置为: {secret_key.secret_key}')
            return redirect('bike:secret_key_management')
        else:
            messages.error(request, '表单验证失败，请检查输入信息。')
    else:
        form = ViolationSecretKeyForm()
    
    # 获取秘钥历史记录
    key_history = ViolationSecretKey.objects.all().order_by('-created_at')[:10]
    
    context = {
        'form': form,
        'current_key': current_key,
        'key_history': key_history,
    }
    
    return render(request, 'admin/secret_key_management.html', context)


def mobile_bike_detail_by_number(request, bike_number):
    """手机端自行车详情页面（通过自行车编号访问）"""
    bike = get_object_or_404(Bicycle, bike_number=bike_number)
    
    # 检查是否需要秘钥验证
    active_key = ViolationSecretKey.get_active_key()
    need_secret_key = active_key is not None
    
    # 检查是否是编辑模式
    edit_mode = request.GET.get('edit') == 'true'
    
    if request.method == 'POST':
        action = request.POST.get('action')
        
        if action == 'edit_bike':
            # 编辑自行车信息
            print(f"编辑自行车(按编号) - POST请求，需要秘钥: {need_secret_key}")
            print(f"POST数据: {request.POST}")
            print(f"FILES数据: {request.FILES}")
            
            if need_secret_key:
                edit_form = BicycleEditFormWithSecret(request.POST, request.FILES, instance=bike)
            else:
                edit_form = BicycleForm(request.POST, request.FILES, instance=bike)
                
            print(f"编辑表单验证结果: {edit_form.is_valid()}")
            if not edit_form.is_valid():
                print(f"编辑表单错误: {edit_form.errors}")
                
            if edit_form.is_valid():
                edit_form.save()
                messages.success(request, '自行车信息更新成功！')
                return redirect('bike:mobile_bike_detail_by_number', bike_number=bike_number)
            else:
                # 显示表单错误
                for field, errors in edit_form.errors.items():
                    for error in errors:
                        messages.error(request, f'{field}: {error}')
                edit_mode = True  # 保持编辑模式
        else:
            # 提交违章信息
            print(f"违章提交(按编号) - POST请求，需要秘钥: {need_secret_key}")
            print(f"POST数据: {request.POST}")
            print(f"FILES数据: {request.FILES}")
            
            if need_secret_key:
                form = ViolationFormWithSecret(request.POST, request.FILES)
            else:
                form = ViolationForm(request.POST, request.FILES)
                
            print(f"表单验证结果: {form.is_valid()}")
            if not form.is_valid():
                print(f"表单错误: {form.errors}")
                
            if form.is_valid():
                violation = form.save(commit=False)
                violation.bicycle = bike
                violation.save()
                messages.success(request, '违章信息提交成功！')
                return redirect('bike:mobile_bike_detail_by_number', bike_number=bike_number)
            else:
                # 显示表单错误
                for field, errors in form.errors.items():
                    for error in errors:
                        messages.error(request, f'{field}: {error}')
    else:
        if need_secret_key:
            form = ViolationFormWithSecret()
            edit_form = BicycleEditFormWithSecret(instance=bike)
        else:
            form = ViolationForm()
            edit_form = BicycleForm(instance=bike)
    
    # 获取该自行车的违章记录
    violations = bike.violations.all().order_by('-created_at')
    
    context = {
        'bike': bike,
        'form': form,
        'edit_form': edit_form,
        'violations': violations,
        'need_secret_key': need_secret_key,
        'edit_mode': edit_mode,
    }
    
    return render(request, 'mobile/bike_detail.html', context)


@login_required
def secret_key_management(request):
    """管理秘钥设置"""
    # 检查用户权限 - 只有超级管理员可以设置秘钥
    try:
        college_user = CollegeUser.objects.get(user=request.user)
        if not college_user.is_super_admin:
            messages.error(request, '只有超级管理员可以设置管理秘钥！')
            return redirect('bike:admin_dashboard')
    except CollegeUser.DoesNotExist:
        messages.error(request, '只有超级管理员可以设置管理秘钥！')
        return redirect('bike:admin_dashboard')
    
    # 获取当前激活的秘钥
    current_key = ViolationSecretKey.get_active_key()
    
    if request.method == 'POST':
        form = ViolationSecretKeyForm(request.POST)
        if form.is_valid():
            # 禁用所有现有秘钥
            ViolationSecretKey.objects.filter(is_active=True).update(is_active=False)
            
            # 创建新秘钥
            secret_key = form.save(commit=False)
            secret_key.created_by = request.user
            secret_key.save()
            
            messages.success(request, f'管理秘钥已设置为: {secret_key.secret_key}')
            return redirect('bike:secret_key_management')
        else:
            messages.error(request, '表单验证失败，请检查输入信息。')
    else:
        form = ViolationSecretKeyForm()
    
    # 获取秘钥历史记录
    key_history = ViolationSecretKey.objects.all().order_by('-created_at')[:10]
    
    context = {
        'form': form,
        'current_key': current_key,
        'key_history': key_history,
    }
    
    return render(request, 'admin/secret_key_management.html', context)
